import type { LocalVersionItem, ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { PgsqlMirror } from "@/modules/dev-env/database/pgsql/pgsql-mirror.ts";
import type { UnzipCompleteArgs } from "@common/archives-file-types";
import { moveTempDir0ToVersionDir } from "@/modules/dev-env/common/install-utils.ts";
import { DatabaseEnvStore } from "@/modules/dev-env/database/common/database-env-store.ts";
import semver from "semver";
import { useSettingStore } from "@/store/setting-store.ts";
import { rmdirViaCmd } from "@/util/system-utils.ts";
import type { EnvTableAction } from "@/modules/dev-env/store/types.ts";
import { openInTerminal } from "@/util/system-utils2.ts";
import PgsqlSettings from "./pgsql-settings.vue";

export class PgsqlEnvStore extends DatabaseEnvStore<PgsqlEnvStore> {
  constructor() {
    super("pgsql");
    this.icon = "icon-postgresql";

    this.pageConfig = {
      showCurrentAction: false,
    };

    this.tableActions = this._tableActions();
    this.settingsComponent = PgsqlSettings;
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "config-install",
        icon: "icon-setting",
        name: "配置/安装",
        onClick: version => (this.proxy.selectedItem = version),
      },
      {
        key: "open-in-terminal",
        name: "在终端打开",
        icon: "icon-terminal",
        onClick: version => openInTerminal(version.installPath, { subPath: ["bin"] }),
      },
    ];
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [new PgsqlMirror()];
  }

  protected compareVersion(a: LocalVersionItem, b: LocalVersionItem): number {
    return semver.compare(this._getVersion(b.version), this._getVersion(a.version));
  }

  private _getVersion(v: string) {
    const [major, minor, patch = "0"] = v.split(".");
    return `${major}.${minor}.${patch}`;
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    const pgCtl = path.join(versionDir, "bin/pg_ctl.exe");
    if (!(await native.fs.exists(pgCtl))) {
      return undefined;
    }

    const version = path.basename(versionDir);
    return { version, installPath: versionDir };
  }

  async afterUnzipComplete(e: UnzipCompleteArgs, version: ToolInstallVersionItem) {
    const versionDir = await moveTempDir0ToVersionDir(e.fileDir, this.installDir, version);

    // 删除pgAdmin
    const settings = useSettingStore();
    if (settings.pgDeletePgAdmin) {
      const subFiles = await native.fs.readdir(versionDir);
      for (const it of subFiles) {
        if (path.basename(it).includes("pgAdmin")) {
          await rmdirViaCmd(it);
        }
      }
    }
  }

  protected async deleteVersionFile(version: LocalVersionItem): Promise<void> {
    await rmdirViaCmd(version.installPath);
  }
}
